<?php
namespace app\common\model;
use think\model\concern\SoftDelete;
class Transfer extends \think\Model
{
    protected $resultSetType = 'collection';
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    //关联用户信息表
    public function messageInfo()
    {
        return $this->hasOne('Message','id','message_id');
    }

    public function accountInfo()
    {
        return $this->hasOne('account','id','to_account_id');
    }

    public function buildingInfo()
    {
        return $this->hasOne('building','id','building_id')->field('id,name');
    }

    /**
     * 选择目标楼盘转介用户
     * @param string project 目标楼盘ID
     * @param int message_id 转介用户
     * @param array 返回信息
     */
    public function inserts($loginInfo){
        $data = input('param.');
        if (!$data['building_id'])
            return [
               'message' =>'转介楼盘不能为空'
            ];
        $check = $this -> check($data,$loginInfo);
        if ($check['code'] != '1')
            return $check;
        $userInfo = $check['userInfo'];

        $buildingInfo = \app\common\model\Building::where('id',$data['building_id'])->find();
        //全民和二级渠道公司优先给负责人
        if(in_array($loginInfo['role'],['24','25','33'])){
                //获取所属负责人
                switch ($loginInfo['role']){
                        //二级渠道公司
                    case '24':
                        if ($loginInfo['distribute'])
                            if (strpos($loginInfo['distributeInfo']['style'],(string)$buildingInfo['list']) !==false)
                                $toAccountID = $loginInfo['distribute'];
                        break;
                        //二级客户专员
                    case  '25':
                        $higher = $loginInfo -> higher;
                        $higherInfo = \app\common\model\Account::where('id',$higher['a_id'])->find();
                        if ($higherInfo['distribute'])
                            if (strpos($higherInfo['distributeInfo']['style'],(string)$buildingInfo['list']) !==false)
                                $toAccountID = $higherInfo['distributeInfo']['id'];
                        break;
                        //全民经纪人
                    case '33':
                        $higher = $loginInfo -> higher;
                        $higherInfo = \app\common\model\Account::where('id',$higher['a_id'])->find();
                        //代理 给内场/外场/部门经理
                        if (in_array($higherInfo['role'],['7','9']) ){
                            if (strpos($higherInfo['project'],(string)$buildingInfo['id']) !==false)
                                $toAccountID = $higherInfo['id'];
                        }
                        //渠道 给驻场，客服
                        elseif (in_array($higherInfo['role'],['22','26','23','27'])){
                            if (strpos($higherInfo['style'],(string)$buildingInfo['list']) !==false)
                                $toAccountID = $higherInfo['id'];
                        }
                        break;
                }
        }

        //正常转介
        if (!$toAccountID){
            //给代理转
            if ($buildingInfo['company'] == '泰和天浩有限公司'){
                //获取目标楼盘所有的内场置业顾问
                $findAgent[] = ['project','eq',$data['building_id']];
                $findAgent[] = ['role','eq',7];
                $findAgent[] = ['id','neq',$loginInfo['id']];
                $allAgent = \app\common\model\Account::where($findAgent)->order('id desc')->column('id');
            }
            //给渠道转
            else{
                //获取目标公司的所有客户专员
                if ($buildingInfo['company'] =='罗宅网络科技有限公司'){
                    $role = 30;
                    $channel_role = ['23','27'];
                }
                else{
                    $role = 21;
                    $channel_role = ['23','27'];
                }
                $step1 = \app\common\model\Account::with('lower.BInfo.lower.BInfo')->order('id desc')->where('role',$role)->find();
                $allAgent = [];
                foreach ($step1['lower'] as $value){
                    if (in_array($value['b_info']['role'],$channel_role) )
                        $allAgent[] = $value['b_id'];
                    foreach ($value['b_info']['lower'] as $item){
                        if (in_array($item['b_info']['role'],$channel_role) )
                            $allAgent[] = $item['b_id'];
                    }
                }

                //删除自己
                $allAgent = array_values(array_diff($allAgent,[$loginInfo['id']]));
            }

            if (!$allAgent)
                return [
                    'message' => '该楼盘没有经纪人'
                ];

            //获取已转介用户个数
            $allTransfer = $this->withTrashed() -> where('to_account_id','in',$allAgent)->count();
            //下一个转介
            if (($allTransfer+1)<=count($allAgent)){
                $toAccountID = $allAgent[$allTransfer];
            }
            else{
                $toAccountID = $allAgent[($allTransfer+1)%count($allAgent)];
            }
        }

        $checkSuccess = $this -> success($userInfo,$toAccountID,$buildingInfo);
        if ($checkSuccess !== true){
            foreach ($allAgent as $value){
                $findCheck[] = ['telephone','eq',$userInfo['telephone']];
                $findCheck[] = ['account_id','eq',$value];
                $check = \app\common\model\Message::where($findCheck)->find();
                if (!$check){
                    $toAccountID = $value;
                    $mark = '1';
                    break;
                }
            }

            if ($mark){
                $this -> success($userInfo,$toAccountID,$buildingInfo);
            }
            else{
                return [
                    'message' => '对方已有该用户，转介失败'
                ];
            }
        }


        return [
            'code' => '1',
            'message' => '转介成功'
        ];
    }


    /**
     * 选择目标经纪人转介用户
     */
    public function inner_inserts($loginInfo){
        $data = input('param.');
        if (!$data['account_id'])
            return [
                'message' => '目标转介经纪人不能为空'
            ];
        $check = $this -> check($data,$loginInfo);
        if ($check['code'] !== '1')
            return $check;


        $userInfo = $check['userInfo'];
        $buildingInfo = \app\common\model\Building::get($userInfo['building']);
        $checkSuccess = $this -> success($userInfo,$data['account_id'],$buildingInfo);
        if ($checkSuccess !== true)
            return $checkSuccess;
        return [
            'code' => '1',
            'message' => '转介成功'
        ];
    }

    //转介前置检查
    public function check($data,$loginInfo){
        if (!$data['message_id'])
            return [
                'message' =>'转介用户不能为空'
            ];
        $check = $this -> where([
            'message_id' => $data['message_id'],
        ])->find();
        if ($check)
            return [
                'message' => '该用户正在转介中'
            ];
        $userInfo = \app\common\model\Message::where('id',$data['message_id'])->find();
        if ($userInfo['account_id'] != $loginInfo['id'])
            //部门经理可以转介
            if (!in_array($loginInfo['role'],['8']))
                return [
                    'message' => '无权操作该用户'
                ];
        return [
            'code' => '1',
            'userInfo' => $userInfo
        ];
    }

    /**
     * 选择目标经纪人转介用户
     * @param string $userInfo 被转介用户
     * @param string $toAccountID 接收的经纪人
     * @param string $buildingInfo 接收的楼盘
     */
    public function success($userInfo,$toAccountID,$buildingInfo)
    {
        $toAccountInfo = \app\common\model\Account::where('id',$toAccountID)->find();
        if (!$toAccountInfo)
            return [
                'message' => '目标经纪人不存在'
            ];
        $findCheck[] = ['telephone','eq',$userInfo['telephone']];
        $findCheck[] = ['account_id','eq',$toAccountID];
        $check = \app\common\model\Message::where($findCheck)->find();
        //查看其他人是否录入过该用户
        if ($check)
            return [
                'message' => '对方已有该用户，转介失败'
            ];
        $this -> save([
            'message_id' => $userInfo['id'],
            'to_account_id' => $toAccountID,
            'building_id' => $buildingInfo['id'],
            'date' => time(),
        ]);

        //修改用户意向楼盘
        \app\common\model\Message::where('id', $userInfo['id'])
            ->update(['building' => $buildingInfo['id']]);


        //发送通知短信
        $send = new  \app\common\logic\Send();
        $send -> inform_transfer($toAccountInfo['telephone'],$userInfo['name'],$userInfo['telephone']);

        $WxMini =new \app\common\logic\WxMini();
        //发送小程序通知（接受）
        if($toAccountInfo['open_id']){
            $sendData = [
                'keyword1' => ['value' => $userInfo['name']],
                'keyword2' => ['value' => $userInfo['telephone']],
                'keyword3' => ['value' => $buildingInfo['name']],
                'keyword4' => ['value' => date('Y-m-d H:i:s')],
                'keyword5' => ['value' => '转介用户'],
            ];
            $WxMini -> sendNotify($toAccountInfo['open_id'],1,'pages/transfer/transfer',$sendData);
        }
        return true;
    }

    //取消转介
    public function dels(){
        $id = input('id');
        $info = $this -> with('messageInfo,accountInfo') -> where('id',$id)->find();
        if ($info){
            if (in_array($info['message_info']['status'],['已定','已买']))
                return [
                    'message' => '已定/已买状态不能撤回'
                ];
            $this -> destroy($id);
        }
        else{
            return [
                'message' => '已撤回'
            ];
        }


        //发送通知短信
        $send = new  \app\common\logic\Send();
        $send -> inform_transfer($info['account_info']['telephone'],$info['message_info']['name'],$info['message_info']['telephone'],false);
        return [
            'code' => '1',
            'message' => '撤回成功',
        ];
    }

}